﻿using System;

namespace Gonte.Networking.Servers
{
    /// <summary>
    /// Implements a chat server
    /// </summary>
    public class ChatServer
        : TcpServer
    {
        public override ClientData CreateClientData()
        {
            return new ChatClientData();
        }

        public override void HandleRequest(NetworkStreamReaderWriter readerWriter, string request, bool hasMoreData)
        {
            ChatClientData clientData = (ChatClientData)readerWriter.ClientData;

            if (clientData.IsSendingUserName)
            {
                clientData.UserName = request;

                Broadcast(string.Format("{0} has joined the chat.", clientData.UserName));
            }
            else
            {
                Broadcast(string.Format("{0}> {1}{2}", clientData.UserName, request, Environment.NewLine));
            }
        }

        public override void HandleClientDisconnected(NetworkStreamReaderWriter readerWriter)
        {
            ChatClientData clientData = (ChatClientData)readerWriter.ClientData;

            Broadcast(string.Format("{0} has left the chat.", clientData.UserName));

            base.HandleClientDisconnected(readerWriter);
        }

        internal class ChatClientData
            : ClientData
        {
            public string UserName; // The name of the user
            public bool IsSendingUserName = true;
        }
    }
}
